const {
  deleteData,
  page,
  list,
} = require("../../../api/index.js")
const utils = require("../../../utils/index.js")

Page({
  /**
   * 页面的初始数据
   */
  data: {
    projectList: [],
    pageNum: 1,
    pageSize: 10,
    total: 0,
    flag: true, // 防抖开关 防止用户不停的下拉
    baseURL: wx.getStorageSync('baseURL') + "/",
    userid: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.setData({
      userid: wx.getStorageSync('userid')
    })
    this.getMyProjects()
  },

  /**
   * 获取我的项目列表
   */
  async getMyProjects() {
    const obj = {
      page: this.data.pageNum,
      limit: this.data.pageSize,
      sfsh: "是"
    }
    
    // 添加用户ID筛选条件
    obj['userid'] = this.data.userid
    
    obj["sort"] = "tijiaoshijian"
    obj["order"] = "desc"

    try {
      const resList = await list("xiangmuxinxi", obj)
      if (resList.code == 0) {
        let mylist = this.data.projectList
        // 处理图片路径
        let resData = resList.data.list.map(item => {
          item.xiangmutupian?.indexOf('http') !== -1 ? item.xiangmutupian : item.xiangmutupian = this.data.baseURL + item.xiangmutupian?.split(",")[0].replace('upload', 'flie')
          return item
        })

        if (this.data.pageNum == 1) {
          mylist = []
        }

        // 新旧数据合并
        let resultdata
        if (resList.data.list.length > 0) {
          resultdata = this.data.projectList.concat(resData)
        }

        if (this.data.pageNum < resList.data.totalPage) {
          this.setData({
            pageNum: obj.page + 1,
            flag: true
          })
        } else {
          this.setData({
            flag: false
          })
        }

        this.setData({
          projectList: resultdata,
          total: resList.total
        })
      }
    } catch (error) {
      console.error('获取项目列表失败:', error)
      wx.showToast({
        title: '获取项目列表失败',
        icon: 'error'
      })
    }
  },

  /**
   * 编辑项目
   */
  editProject(e) {
    const projectId = e.currentTarget.dataset.id
    getApp().globalData.detailId = projectId
    wx.navigateTo({
      url: `/pages/xiangmuxinxi/update-and-add?id=${projectId}`
    })
  },

  /**
   * 删除项目
   */
  deleteProject(e) {
    const projectId = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个项目吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const result = await deleteData('xiangmuxinxi', projectId)
            if (result.code === 0) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              this.setData({
                pageNum: 1,
                projectList: []
              })
              this.getMyProjects() // 刷新列表
            } else {
              wx.showToast({
                title: '删除失败',
                icon: 'error'
              })
            }
          } catch (error) {
            wx.showToast({
              title: '删除失败',
              icon: 'error'
            })
          }
        }
      }
    })
  },

  /**
   * 查看项目详情
   */
  viewProjectDetail(e) {
    const projectId = e.currentTarget.dataset.id
    getApp().globalData.detailId = projectId
    wx.navigateTo({
      url: `/pages/xiangmuxinxi/detail?id=${projectId}`
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.flag) {
      this.setData({
        flag: false
      })
      this.getMyProjects()
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      projectList: []
    })
    this.getMyProjects()
    wx.stopPullDownRefresh()
  }
}) 